//
//  IMGameStrategyModels.m
//  DualMediationSDK
//
//  产品策略相关模型实现
//  Created by YeJary on 2025/7/15.
//

#import "IMGameStrategyModels.h"

@implementation IMGameStrategyRequest

+ (instancetype)requestWithAppId:(NSString *)appId uuid:(NSString *)uuid {
    IMGameStrategyRequest *request = [[IMGameStrategyRequest alloc] init];
    request.app_id = appId;
    request.uuid = uuid;
    return request;
}

- (NSDictionary *)toDictionary {
    return @{
        @"app_id": self.app_id ?: @"",
        @"uuid": self.uuid ?: @""
    };
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameStrategyRequest: app_id=%@, uuid=%@>", self.app_id, self.uuid];
}

@end

@implementation IMGameConditions

+ (instancetype)conditionsFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    IMGameConditions *conditions = [[IMGameConditions alloc] init];
    
    // 处理cur_level，可能是字符串或数字
    id curLevelValue = dictionary[@"cur_level"];
    if ([curLevelValue isKindOfClass:[NSString class]]) {
        conditions.cur_level = @([curLevelValue integerValue]);
    } else if ([curLevelValue isKindOfClass:[NSNumber class]]) {
        conditions.cur_level = curLevelValue;
    }
    
    // 处理level_interval，可能是字符串或数字
    id levelIntervalValue = dictionary[@"level_interval"];
    if ([levelIntervalValue isKindOfClass:[NSString class]]) {
        conditions.level_interval = @([levelIntervalValue integerValue]);
    } else if ([levelIntervalValue isKindOfClass:[NSNumber class]]) {
        conditions.level_interval = levelIntervalValue;
    }
    
    // 处理ad_mob_first，可能是字符串或数字或布尔值
    id adMobFirstValue = dictionary[@"ad_mob_first"];
    if ([adMobFirstValue isKindOfClass:[NSString class]]) {
        conditions.ad_mob_first = @([adMobFirstValue boolValue]);
    } else if ([adMobFirstValue isKindOfClass:[NSNumber class]]) {
        conditions.ad_mob_first = adMobFirstValue;
    }
    
    // 处理其他扩展条件，包括product_id、install_day等
    NSMutableDictionary *additionalConditions = [NSMutableDictionary dictionary];
    NSArray *knownKeys = @[@"cur_level", @"level_interval", @"ad_mob_first"];
    
    for (NSString *key in dictionary.allKeys) {
        if (![knownKeys containsObject:key]) {
            id value = dictionary[key];
            // 对于数字类型的字段，确保正确转换
            if ([key isEqualToString:@"install_day"]) {
                if ([value isKindOfClass:[NSString class]]) {
                    additionalConditions[key] = @([value integerValue]);
                } else if ([value isKindOfClass:[NSNumber class]]) {
                    additionalConditions[key] = value;
                } else {
                    additionalConditions[key] = @(0); // 默认值
                }
            } else {
                // 对于字符串类型的字段如product_id，直接赋值
                additionalConditions[key] = value;
            }
        }
    }
    
    if (additionalConditions.count > 0) {
        conditions.additionalConditions = [additionalConditions copy];
    }
    
    return conditions;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameConditions: cur_level=%@, level_interval=%@, ad_mob_first=%@, additional=%@>", 
            self.cur_level, self.level_interval, self.ad_mob_first, self.additionalConditions];
}

@end

@implementation IMGameActions

+ (instancetype)actionsFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    IMGameActions *actions = [[IMGameActions alloc] init];
    actions.level_combine = dictionary[@"level_combine"];
    
    // 处理其他扩展动作，包括discount_pack等
    NSMutableDictionary *additionalActions = [NSMutableDictionary dictionary];
    NSArray *knownKeys = @[@"level_combine"];
    
    for (NSString *key in dictionary.allKeys) {
        if (![knownKeys containsObject:key]) {
            additionalActions[key] = dictionary[key];
        }
    }
    
    if (additionalActions.count > 0) {
        actions.additionalActions = [additionalActions copy];
    }
    
    return actions;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameActions: level_combine=%@, additional=%@>", 
            self.level_combine, self.additionalActions];
}

@end

@implementation IMGameStrategy

+ (instancetype)strategyFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[GameStrategy] 策略字典为空或类型错误");
        return nil;
    }
    
    IMGameStrategy *strategy = [[IMGameStrategy alloc] init];
    // 处理rate，可能是字符串或数字
    id rateValue = dictionary[@"rate"];
    if ([rateValue isKindOfClass:[NSString class]]) {
        strategy.rate = [rateValue integerValue];
    } else if ([rateValue isKindOfClass:[NSNumber class]]) {
        strategy.rate = [rateValue integerValue];
    } else {
        strategy.rate = 0; // 默认值
        NSLog(@"[GameStrategy] rate类型异常: %@", rateValue);
    }
    strategy.strategy_id = dictionary[@"strategy_id"];
    
    // 解析策略条件
    NSDictionary *conditionsDict = dictionary[@"conditions"];
    if (conditionsDict && [conditionsDict isKindOfClass:[NSDictionary class]]) {
        strategy.conditions = [IMGameConditions conditionsFromDictionary:conditionsDict];
        if (!strategy.conditions) {
            NSLog(@"[GameStrategy] conditions解析失败: %@", conditionsDict);
        }
    } else if (conditionsDict) {
        NSLog(@"[GameStrategy] conditions字段不是字典类型: %@", conditionsDict);
    }
    
    // 解析策略动作
    NSDictionary *actionsDict = dictionary[@"actions"];
    if (actionsDict && [actionsDict isKindOfClass:[NSDictionary class]]) {
        strategy.actions = [IMGameActions actionsFromDictionary:actionsDict];
        if (!strategy.actions) {
            NSLog(@"[GameStrategy] actions解析失败: %@", actionsDict);
        }
    } else if (actionsDict) {
        NSLog(@"[GameStrategy] actions字段不是字典类型: %@", actionsDict);
    }
    
    return strategy;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameStrategy: rate=%ld, strategy_id=%@, conditions=%@, actions=%@>", 
            (long)self.rate, self.strategy_id, self.conditions, self.actions];
}

@end

@implementation IMGameSceneStrategy

+ (instancetype)sceneStrategyFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[GameStrategy] 场景策略字典为空或类型错误");
        return nil;
    }
    
    IMGameSceneStrategy *sceneStrategy = [[IMGameSceneStrategy alloc] init];
    sceneStrategy.scene_name = dictionary[@"scene_name"];
    sceneStrategy.scene_desc = dictionary[@"scene_desc"];
    // 处理user_type，可能是字符串或数字
    id userTypeValue = dictionary[@"user_type"];
    if ([userTypeValue isKindOfClass:[NSString class]]) {
        sceneStrategy.user_type = [userTypeValue integerValue];
    } else if ([userTypeValue isKindOfClass:[NSNumber class]]) {
        sceneStrategy.user_type = [userTypeValue integerValue];
    } else {
        sceneStrategy.user_type = 0; // 默认值
        NSLog(@"[GameStrategy] user_type类型异常: %@", userTypeValue);
    }
    
    // 解析国家/地区数组
    NSArray *countryArray = dictionary[@"country"];
    if (countryArray && [countryArray isKindOfClass:[NSArray class]]) {
        sceneStrategy.country = countryArray;
    } else {
        NSLog(@"[GameStrategy] country字段不是数组类型: %@", countryArray);
        sceneStrategy.country = @[]; // 设置默认值
    }
    
    // 解析渠道数组
    NSArray *channelsArray = dictionary[@"channels"];
    if (channelsArray && [channelsArray isKindOfClass:[NSArray class]]) {
        sceneStrategy.channels = channelsArray;
    } else {
        NSLog(@"[GameStrategy] channels字段不是数组类型: %@", channelsArray);
        sceneStrategy.channels = @[]; // 设置默认值
    }
    
    // 解析策略数组
    NSArray *strategyArray = dictionary[@"strategy"];
    if (strategyArray && [strategyArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *strategies = [NSMutableArray array];
        for (int i = 0; i < strategyArray.count; i++) {
            NSDictionary *strategyDict = strategyArray[i];
            if (![strategyDict isKindOfClass:[NSDictionary class]]) {
                NSLog(@"[GameStrategy] 策略数据[%d]不是字典类型: %@", i, strategyDict);
                continue;
            }
            
            IMGameStrategy *strategy = [IMGameStrategy strategyFromDictionary:strategyDict];
            if (strategy) {
                [strategies addObject:strategy];
            } else {
                NSLog(@"[GameStrategy] 策略[%d]解析失败: %@", i, strategyDict);
            }
        }
        sceneStrategy.strategy = [strategies copy];
    } else {
        NSLog(@"[GameStrategy] strategy字段不是数组类型: %@", strategyArray);
        sceneStrategy.strategy = @[]; // 设置默认值
    }
    
    return sceneStrategy;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameSceneStrategy: scene_name=%@, scene_desc=%@, country=%@, user_type=%ld, channels=%@, strategies=%lu>", 
            self.scene_name, self.scene_desc, self.country, (long)self.user_type, self.channels, (unsigned long)self.strategy.count];
}

@end

@implementation IMGameStrategyResponse

+ (instancetype)responseFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[GameStrategy] 响应字典为空或类型错误");
        return nil;
    }
    
    IMGameStrategyResponse *response = [[IMGameStrategyResponse alloc] init];
    // 处理code，可能是字符串或数字
    id codeValue = dictionary[@"code"];
    if ([codeValue isKindOfClass:[NSString class]]) {
        response.code = [codeValue integerValue];
    } else if ([codeValue isKindOfClass:[NSNumber class]]) {
        response.code = [codeValue integerValue];
    } else {
        response.code = 0; // 默认值
    }
    response.message = dictionary[@"message"] ?: @"";
    
    // 解析数据数组
    NSArray *dataArray = dictionary[@"data"];
    if (dataArray && [dataArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *sceneStrategies = [NSMutableArray array];
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary *sceneDict = dataArray[i];
            if (![sceneDict isKindOfClass:[NSDictionary class]]) {
                NSLog(@"[GameStrategy] 场景数据[%d]不是字典类型: %@", i, sceneDict);
                continue;
            }
            
            IMGameSceneStrategy *sceneStrategy = [IMGameSceneStrategy sceneStrategyFromDictionary:sceneDict];
            if (sceneStrategy) {
                [sceneStrategies addObject:sceneStrategy];
            } else {
                NSLog(@"[GameStrategy] 场景策略[%d]解析失败: %@", i, sceneDict);
            }
        }
        response.data = [sceneStrategies copy];
    } else {
        NSLog(@"[GameStrategy] data字段不是数组类型: %@", dataArray);
        response.data = @[]; // 设置为空数组而不是nil
    }
    
    return response;
}

- (BOOL)isSuccess {
    return self.code == 200;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMGameStrategyResponse: code=%ld, message=%@, data_count=%lu>", 
            (long)self.code, self.message, (unsigned long)self.data.count];
}

@end